package cn.wolfcode.wolf2world.service.impl;

import cn.wolfcode.wolf2world.domain.UserStrategyFavoer;
import cn.wolfcode.wolf2world.query.UserStrategyFavoerQueryObject;
import cn.wolfcode.wolf2world.repository.UserStrategyFavoerRepository;
import cn.wolfcode.wolf2world.service.UserStrategyFavoerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author 杨兴健
 * @Date 2020-08-18 13:39
 */
@Service
public class UserStrategyFavoerServiceImpl implements UserStrategyFavoerService {
    @Autowired
    private UserStrategyFavoerRepository userStrategyFavoerRepository;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void save(UserStrategyFavoer userStrategyFavoer) {
        userStrategyFavoer.setId(null);
        userStrategyFavoerRepository.insert(userStrategyFavoer);
    }

    @Override
    public void update(UserStrategyFavoer userStrategyFavoer) {
        userStrategyFavoerRepository.save(userStrategyFavoer);
    }

    @Override
    public void delete(String id) {
        userStrategyFavoerRepository.deleteById(id);
    }

    @Override
    public UserStrategyFavoer get(String id) {
        return userStrategyFavoerRepository.findById(id).orElse(null);
    }

    @Override
    public List<UserStrategyFavoer> list() {
        return userStrategyFavoerRepository.findAll();
    }

    /**
    * 用户攻略收藏高级查询
    * @param qo 查询条件
    * @return
    */
    @Override
    public Page<UserStrategyFavoer> query(UserStrategyFavoerQueryObject qo) {

        Query query = new Query();

        long count = mongoTemplate.count(query, UserStrategyFavoer.class);
        if (count == 0) {
            return Page.empty();
        }

        Pageable pageRequest = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.ASC,"sequence");
        query.with(pageRequest);
        List<UserStrategyFavoer> list = mongoTemplate.find(query, UserStrategyFavoer.class);
        return new PageImpl<UserStrategyFavoer>(list,pageRequest,count);
    }

    /**
     * 新增或编辑用户攻略收藏
     * @param userStrategyFavoer
     */
    @Override
    public void saveOrUpdate(UserStrategyFavoer userStrategyFavoer) {
        if (StringUtils.hasLength(userStrategyFavoer.getId())) {
            //编辑
            this.update(userStrategyFavoer);
        }else {
            //新增
            this.save(userStrategyFavoer);
        }
    }

    /**
     * 根据uid查询
     * @param uid
     * @return
     */
    @Override
    public UserStrategyFavoer findbyUid(String uid) {
        return userStrategyFavoerRepository.findByUid(uid);

    }
}
